<template>
    <div class="terrain-loader">
        <h3>地形数据加载</h3>
        <div class="terrain-info">
            <p><strong>说明：</strong>地形是Cesium的"骨架"，支持多种地形数据服务</p>
            <p>包括全球地形、自定义地形、地形光照和水面效果</p>
        </div>
        
        <!-- 地形服务选择 -->
        <div class="terrain-services">
            <h4>地形服务</h4>
            <div class="services-grid">
                <div v-for="(item, index) in terrainList" :key="index" 
                     class="service-item" 
                     :class="{ 'service-selected': selectedTerrainIndex === index }"
                     @click="selectTerrain(item, index)">
                    <div class="service-preview">
                        <div class="service-icon">{{ item.icon }}</div>
                        <div class="service-overlay" v-show="hoveredServiceIndex === index">
                            <span>{{ item.name }}</span>
                        </div>
                    </div>
                    <div class="service-name" 
                         @mouseenter="hoveredServiceIndex = index"
                         @mouseleave="hoveredServiceIndex = undefined">
                        {{ item.name }}
                    </div>
                </div>
            </div>
        </div>
        
        <div class="terrain-controls">
            <button @click="loadTerrain" class="load-btn" :disabled="!selectedTerrain">
                加载地形
            </button>
            <button @click="clearTerrain" class="clear-btn">
                清除地形
            </button>
        </div>
        
        <!-- 地形效果控制 -->
        <div class="terrain-effects">
            <h4>地形效果</h4>
            <div class="effects-controls">
                <button @click="enableTerrainLighting" class="lighting-btn">启用地形光照</button>
                <button @click="enableWaterMask" class="water-btn">创建水面对象</button>
                <button @click="disableTerrainLighting" class="disable-btn">禁用光照</button>
                <button @click="disableWaterMask" class="disable-btn">禁用水面</button>
                <button @click="flyToWaterArea" class="test-btn">飞行到水域</button>
            </div>
        </div>
        
        <div class="terrain-details">
            <p><strong>服务地址：</strong>{{ terrainUrl }}</p>
            <p><strong>地形名称：</strong>{{ terrainName }}</p>
        </div>
        
        <div class="terrain-status">
            <p>地形状态: <span :class="terrainStatusClass">{{ terrainStatus }}</span></p>
            <p>图层数量: <span :class="layerCountClass">{{ layerCount }}</span></p>
            <p>光照状态: <span :class="lightingStatusClass">{{ lightingStatus }}</span></p>
            <p>水面对象: <span :class="waterStatusClass">{{ waterCount }}</span></p>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, inject, onMounted } from 'vue';
import { XbsjEarthUi } from '../../../../scripts/xbsjEarthUi';
import { SceneTree } from 'xbsj-xe2/dist-node/xe2';
import { ESTerrainLayer, ESGeoWater } from "esobjs-xe2-plugin/dist-node/esobjs-xe2-plugin-main";
import { Message } from "earthsdk-ui";
import { searchMaxZindex, getsceneObjNumfromSceneTree } from '../../../../scripts/general';

const sceneTree = inject('sceneTree') as SceneTree;
const xbsjEarthUi = inject('xbsjEarthUi') as XbsjEarthUi;

// 响应式数据
const terrainStatus = ref('未加载');
const terrainStatusClass = ref('status-unknown');
const layerCount = ref(0);
const layerCountClass = ref('status-unknown');
const lightingStatus = ref('未启用');
const lightingStatusClass = ref('status-unknown');
const waterCount = ref(0);
const waterStatusClass = ref('status-unknown');

const terrainUrl = ref('');
const terrainName = ref('未命名地形');
const terrainList = ref<any[]>([]);
const selectedTerrainIndex = ref(-1);
const hoveredServiceIndex = ref();
const selectedTerrain = ref<any>(null);

// 地形服务数据
const terrainData = [
    {
        id: 'world_terrain',
        name: '全球地形',
        icon: '🌍',
        url: 'Cesium.createWorldTerrain()',
        description: 'Cesium官方全球地形服务，支持光照和水面效果'
    },
    {
        id: 'custom_terrain',
        name: '自定义地形',
        icon: '🏔️',
        url: 'http://localhost:9209/terrain/test/layer.json',
        description: 'CesiumLab TerrainRTS本地地形服务'
    }
];

// 选择地形服务
const selectTerrain = (item: any, index: number) => {
    terrainUrl.value = item.url;
    terrainName.value = item.name;
    selectedTerrainIndex.value = index;
    selectedTerrain.value = item;
};

// 获取Cesium原生Viewer实例
const getCesiumViewer = () => {
    return xbsjEarthUi.activeViewer?.innerViewer?.viewer as any;
};

// 获取或创建地形图层管理文件夹
const getOrCreateTerrainFolder = () => {
    const sceneTree = xbsjEarthUi.getSceneTree();
    if (!sceneTree) {
        throw new Error('场景树不可用');
    }

    // 查找是否已存在地形图层管理文件夹
    const findTerrainFolderTreeItem = (): any => {
        if (sceneTree.root.children) {
            for (const child of sceneTree.root.children) {
                if ((child as any).name === '地形数据加载') {
                    return child;
                }
            }
        }
        return null;
    };

    let terrainFolder = findTerrainFolderTreeItem();

    // 如果不存在，创建新的地形图层管理文件夹
    if (!terrainFolder) {
        terrainFolder = sceneTree.createGroupTreeItem(undefined, undefined, undefined, undefined);
        if (!terrainFolder) {
            throw new Error('无法创建地形图层管理文件夹');
        }
        terrainFolder.name = '地形数据加载';
    }

    return terrainFolder;
};

// 加载地形
const loadTerrain = () => {
    if (!selectedTerrain.value) {
        Message.error('请选择地形服务');
        return;
    }

    try {
        terrainStatus.value = '加载中...';
        terrainStatusClass.value = 'status-loading';

        // 获取最大zIndex
        const maxZindex = searchMaxZindex(sceneTree, 'ESTerrainLayer');
        
        // 获取或创建地形图层管理文件夹
        let terrainFolder = getOrCreateTerrainFolder();
        
        // 创建新的地形图层树项
        const newTreeItem = sceneTree.createSceneObjectTreeItem('ESTerrainLayer', undefined, terrainFolder, 'Inner');
        
        if (!newTreeItem) {
            throw new Error('无法创建地形图层');
        }
        
        // 设置选中状态
        sceneTree.uiTree.clearAllSelectedItems();
        newTreeItem.uiTreeObject.selected = true;
        
        if (!newTreeItem.sceneObject) {
            throw new Error('场景对象不存在');
        }
        
        if (newTreeItem.sceneObject.typeName !== 'ESTerrainLayer') {
            throw new Error('场景对象类型错误');
        }
        
        const sceneObject = newTreeItem.sceneObject as unknown as ESTerrainLayer;
        xbsjEarthUi.propSceneTree = newTreeItem;
        
        // 获取对象编号
        const objNum = getsceneObjNumfromSceneTree(xbsjEarthUi, 'ESTerrainLayer');
        
        // 设置图层属性
        newTreeItem.name = terrainName.value + (objNum + 1);
        
        // 根据不同类型设置URL
        if (selectedTerrain.value.id === 'world_terrain') {
            // 全球地形使用Cesium Ion
            sceneObject.url = "http://223.244.255.52:8090/china_11";
        } else if (selectedTerrain.value.id === 'custom_terrain') {
            // 自定义地形
            sceneObject.url = selectedTerrain.value.url;
        }
        
        sceneObject.zIndex = maxZindex + 1;
        
        // 更新状态
        terrainStatus.value = '加载成功';
        terrainStatusClass.value = 'status-success';
        layerCount.value = objNum + 1;
        layerCountClass.value = 'status-success';
        
    } catch (error) {
        console.error('加载地形失败:', error);
        terrainStatus.value = '加载失败';
        terrainStatusClass.value = 'status-error';
        Message.error('加载地形失败: ' + (error as Error).message);
    }
};

// 清除地形
const clearTerrain = () => {
    try {
        // 获取场景树
        const sceneTree = xbsjEarthUi.getSceneTree();
        if (!sceneTree) {
            console.error('场景树不可用');
            terrainStatus.value = '场景树不可用';
            terrainStatusClass.value = 'status-error';
            return;
        }

        // 查找地形图层管理文件夹
        const findTerrainFolderTreeItem = (): any => {
            if (sceneTree.root.children) {
                for (const child of sceneTree.root.children) {
                    if ((child as any).name === '地形数据加载') {
                        return child;
                    }
                }
            }
            return null;
        };

        let terrainFolder = findTerrainFolderTreeItem();

        if (terrainFolder) {
            // 删除整个地形图层管理文件夹
            try {
                if (typeof terrainFolder.isDestroyed === 'function') {
                    if (!terrainFolder.isDestroyed()) {
                        terrainFolder.detachFromParent();
                    }
                } else if (typeof terrainFolder.isDestroyed === 'boolean') {
                    if (!terrainFolder.isDestroyed) {
                        terrainFolder.detachFromParent();
                    }
                } else {
                    terrainFolder.detachFromParent();
                }
            } catch (folderError) {
                console.warn('删除地形图层管理文件夹失败:', folderError);
            }
        }

        // 更新状态
        terrainStatus.value = '已清除';
        terrainStatusClass.value = 'status-cleared';
        layerCount.value = 0;
        layerCountClass.value = 'status-cleared';
    } catch (error) {
        console.error('清除地形失败:', error);
        terrainStatus.value = '清除失败';
        terrainStatusClass.value = 'status-error';
        Message.error('清除地形失败');
    }
};

// 启用地形光照
const enableTerrainLighting = () => {
    const viewer = getCesiumViewer();
    if (!viewer) {
        console.error('Cesium Viewer不可用');
        lightingStatus.value = 'Viewer不可用';
        lightingStatusClass.value = 'status-error';
        return;
    }

    try {
        // 启用场景光照
        viewer.scene.globe.enableLighting = true;

        // 重新加载所有ESTerrainLayer地形以应用光照
        const sceneTree = xbsjEarthUi.getSceneTree();
        if (sceneTree && sceneTree.root.children) {
            // 查找地形数据加载文件夹
            let terrainFolder = null;
            for (let i = 0; i < sceneTree.root.children.length; i++) {
                const child = sceneTree.root.children.get(i) as any;
                if (child.name === '地形数据加载') {
                    terrainFolder = child;
                    break;
                }
            }
            
            if (terrainFolder && terrainFolder.children) {
                // 遍历所有地形图层
                for (let j = 0; j < terrainFolder.children.length; j++) {
                    const terrainItem = terrainFolder.children.get(j) as any;
                    if (terrainItem && terrainItem.sceneObj && terrainItem.sceneObj.typeName === 'ESTerrainLayer') {
                        // 重新创建地形服务以应用光照
                        const terrainLayer = terrainItem.sceneObj;
                        if (terrainLayer && terrainLayer.url) {
                            try {
                                // 创建支持光照的地形服务
                                const terrainProvider = new (window as any).Cesium.CesiumTerrainProvider({
                                    url: terrainLayer.url,
                                    requestVertexNormals: true,
                                    requestWaterMask: true
                                });
                                
                                // 更新地形服务
                                terrainLayer.terrainProvider = terrainProvider;
                            } catch (terrainError) {
                                console.warn('更新地形服务失败:', terrainError);
                            }
                        }
                    }
                }
            }
        }

        lightingStatus.value = '已启用';
        lightingStatusClass.value = 'status-success';
        console.log('地形光照已启用');
    } catch (error) {
        console.error('启用地形光照失败:', error);
        lightingStatus.value = '启用失败';
        lightingStatusClass.value = 'status-error';
    }
};

// 禁用地形光照
const disableTerrainLighting = () => {
    const viewer = getCesiumViewer();
    if (!viewer) {
        console.error('Cesium Viewer不可用');
        lightingStatus.value = 'Viewer不可用';
        lightingStatusClass.value = 'status-error';
        return;
    }

    try {
        // 禁用场景光照
        viewer.scene.globe.enableLighting = false;

        // 重新加载所有ESTerrainLayer地形以禁用光照
        const sceneTree = xbsjEarthUi.getSceneTree();
        if (sceneTree && sceneTree.root.children) {
            // 查找地形数据加载文件夹
            let terrainFolder = null;
            for (let i = 0; i < sceneTree.root.children.length; i++) {
                const child = sceneTree.root.children.get(i) as any;
                if (child.name === '地形数据加载') {
                    terrainFolder = child;
                    break;
                }
            }
            
            if (terrainFolder && terrainFolder.children) {
                // 遍历所有地形图层
                for (let j = 0; j < terrainFolder.children.length; j++) {
                    const terrainItem = terrainFolder.children.get(j) as any;
                    if (terrainItem && terrainItem.sceneObj && terrainItem.sceneObj.typeName === 'ESTerrainLayer') {
                        // 重新创建地形服务以禁用光照
                        const terrainLayer = terrainItem.sceneObj;
                        if (terrainLayer && terrainLayer.url) {
                            try {
                                // 创建不支持光照的地形服务
                                const terrainProvider = new (window as any).Cesium.CesiumTerrainProvider({
                                    url: terrainLayer.url,
                                    requestVertexNormals: false,
                                    requestWaterMask: true
                                });
                                
                                // 更新地形服务
                                terrainLayer.terrainProvider = terrainProvider;
                            } catch (terrainError) {
                                console.warn('更新地形服务失败:', terrainError);
                            }
                        }
                    }
                }
            }
        }

        lightingStatus.value = '已禁用';
        lightingStatusClass.value = 'status-disabled';
        console.log('地形光照已禁用');
    } catch (error) {
        console.error('禁用地形光照失败:', error);
        lightingStatus.value = '禁用失败';
        lightingStatusClass.value = 'status-error';
    }
};

// 启用水面效果
const enableWaterMask = () => {
    const viewer = getCesiumViewer();
    if (!viewer) {
        console.error('Cesium Viewer不可用');
        waterCount.value = 0;
        waterStatusClass.value = 'status-error';
        return;
    }

    try {
        // 获取或创建地形图层管理文件夹
        let terrainFolder = getOrCreateTerrainFolder();
        
        // 创建地理水面对象
        const waterObject = xbsjEarthUi.createSceneObject(ESGeoWater) as ESGeoWater;
        if (!waterObject) {
            throw new Error('无法创建地理水面对象');
        }
        
        // 获取最大zIndex
        const maxZindex = searchMaxZindex(sceneTree, 'ESGeoWater');
        
        // 创建水面图层树项
        const newTreeItem = sceneTree.createSceneObjectTreeItem('ESGeoWater', undefined, terrainFolder, 'Inner');
        if (!newTreeItem) {
            throw new Error('无法创建水面图层树项');
        }
        
        // 设置选中状态
        sceneTree.uiTree.clearAllSelectedItems();
        newTreeItem.uiTreeObject.selected = true;
        
        // 设置水面对象属性
        const objNum = getsceneObjNumfromSceneTree(xbsjEarthUi, 'ESGeoWater');
        newTreeItem.name = '地理水面' + (objNum + 1);
        
        // 设置水面对象的基本属性
        waterObject.name = newTreeItem.name;
        
        // 设置水面模式为动态水面
        (waterObject as any).mode = 'DynamicWater';
        
        // 启用编辑状态，让用户手动绘制水面区域
        waterObject.editing = true;
        
        // 监听编辑状态变化
        waterObject.editingChanged.disposableOnce(() => {
            if (waterObject && waterObject.editing === false) {
                console.log('水面对象编辑完成');
                // 不自动飞行，保持在当前位置
            }
        });
        
        // 设置水面颜色
        (waterObject as any).color = new (window as any).Cesium.Color(0.0, 0.5, 1.0, 0.8); // 蓝色半透明

        waterCount.value = getsceneObjNumfromSceneTree(xbsjEarthUi, 'ESGeoWater');
        waterStatusClass.value = 'status-success';
        console.log('地理水面对象已创建，请在场景中点击绘制水面区域，绘制完成后将保持在当前位置');
    } catch (error) {
        console.error('启用水面效果失败:', error);
        waterCount.value = 0;
        waterStatusClass.value = 'status-error';
    }
};

// 禁用水面效果
const disableWaterMask = () => {
    try {
        // 获取场景树
        const sceneTree = xbsjEarthUi.getSceneTree();
        if (!sceneTree) {
            console.error('场景树不可用');
            waterCount.value = 0;
            waterStatusClass.value = 'status-error';
            return;
        }

        // 查找地形图层管理文件夹
        let terrainFolder = null;
        if (sceneTree.root.children) {
            for (let i = 0; i < sceneTree.root.children.length; i++) {
                const child = sceneTree.root.children.get(i) as any;
                if (child.name === '地形数据加载') {
                    terrainFolder = child;
                    break;
                }
            }
        }

        if (terrainFolder && terrainFolder.children) {
            // 查找并删除所有水面对象
            const waterItems = [];
            for (let j = 0; j < terrainFolder.children.length; j++) {
                const item = terrainFolder.children.get(j) as any;
                if (item && item.sceneObj && item.sceneObj.typeName === 'ESGeoWater') {
                    waterItems.push(item);
                }
            }
            
            // 删除所有水面对象
            waterItems.forEach((waterItem: any) => {
                try {
                    if (waterItem.sceneObj) {
                        xbsjEarthUi.destroySceneObject(waterItem.sceneObj);
                    }
                    if (typeof waterItem.isDestroyed === 'function') {
                        if (!waterItem.isDestroyed()) {
                            waterItem.detachFromParent();
                        }
                    } else if (typeof waterItem.isDestroyed === 'boolean') {
                        if (!waterItem.isDestroyed) {
                            waterItem.detachFromParent();
                        }
                    } else {
                        waterItem.detachFromParent();
                    }
                    console.log('已删除水面对象:', waterItem.name);
                } catch (deleteError) {
                    console.warn('删除水面对象失败:', deleteError);
                }
            });
        }

        waterCount.value = getsceneObjNumfromSceneTree(xbsjEarthUi, 'ESGeoWater');
        waterStatusClass.value = 'status-disabled';
        console.log('地理水面效果已禁用');
    } catch (error) {
        console.error('禁用水面效果失败:', error);
        waterCount.value = 0;
        waterStatusClass.value = 'status-error';
    }
};

// 飞行到水域区域
const flyToWaterArea = () => {
    const viewer = getCesiumViewer();
    if (!viewer) {
        console.error('Cesium Viewer不可用');
        return;
    }

    try {
        // 飞行到长江流域（有大量水域的区域）
        const rectangle = new (window as any).Cesium.Rectangle(
            (window as any).Cesium.Math.toRadians(110.0),
            (window as any).Cesium.Math.toRadians(30.0),
            (window as any).Cesium.Math.toRadians(120.0),
            (window as any).Cesium.Math.toRadians(35.0)
        );
        
        viewer.scene.camera.flyTo({ 
            destination: rectangle,
            duration: 3.0
        });
        
        console.log('已飞行到长江流域区域，这里应该有明显的水面效果');
    } catch (error) {
        console.error('飞行到水域区域失败:', error);
    }
};

// 组件挂载时加载地形服务列表
onMounted(() => {
    try {
        // 使用本地静态数据
        terrainList.value = terrainData;
        
        // 检查Viewer状态
        if (sceneTree) {
            terrainStatus.value = '就绪';
            terrainStatusClass.value = 'status-ready';
            layerCount.value = getsceneObjNumfromSceneTree(xbsjEarthUi, 'ESTerrainLayer');
            layerCountClass.value = 'status-ready';
            lightingStatus.value = '就绪';
            lightingStatusClass.value = 'status-ready';
            waterCount.value = getsceneObjNumfromSceneTree(xbsjEarthUi, 'ESGeoWater');
            waterStatusClass.value = 'status-ready';
        } else {
            terrainStatus.value = 'SceneTree不可用';
            terrainStatusClass.value = 'status-error';
            lightingStatus.value = 'SceneTree不可用';
            lightingStatusClass.value = 'status-error';
            waterCount.value = 0;
            waterStatusClass.value = 'status-error';
        }
    } catch (error) {
        console.error('加载地形服务列表失败:', error);
        terrainStatus.value = '服务列表加载失败';
        terrainStatusClass.value = 'status-error';
    }
});
</script>

<style scoped>
.terrain-loader {
    width: 277px;
    box-sizing: border-box;
    padding: 15px;
    background-color: #1a1a1a;
    border-radius: 8px;
}

.terrain-info {
    padding: 12px;
    background-color: #2a2a2a;
    border-radius: 6px;
    margin-bottom: 15px;
    font-size: 14px;
    color: #e0e0e0;
}

.terrain-services {
    margin-bottom: 20px;
}

.terrain-services h4 {
    margin-bottom: 12px;
    color: #e0e0e0;
    font-size: 16px;
}

.services-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 8px;
    max-height: 200px;
    overflow-y: auto;
}

.service-item {
    cursor: pointer;
    border: 2px solid transparent;
    border-radius: 6px;
    transition: all 0.3s ease;
}

.service-item:hover {
    border-color: #4CAF50;
}

.service-selected {
    border-color: #2196F3 !important;
    background-color: rgba(33, 150, 243, 0.1);
}

.service-preview {
    position: relative;
    width: 100%;
    height: 60px;
    overflow: hidden;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #333;
}

.service-icon {
    font-size: 24px;
}

.service-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.7);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 12px;
    text-align: center;
}

.service-name {
    padding: 4px;
    font-size: 12px;
    color: #e0e0e0;
    text-align: center;
    word-break: break-all;
}

.terrain-controls {
    display: flex;
    gap: 10px;
    margin-bottom: 15px;
}

.load-btn,
.clear-btn {
    flex: 1;
    padding: 10px 16px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-size: 14px;
    font-weight: bold;
    transition: all 0.3s ease;
}

.load-btn {
    background-color: #4CAF50;
    color: white;
}

.load-btn:hover:not(:disabled) {
    background-color: #45a049;
}

.load-btn:disabled {
    background-color: #666;
    cursor: not-allowed;
}

.clear-btn {
    background-color: #f44336;
    color: white;
}

.clear-btn:hover {
    background-color: #da190b;
}

.terrain-effects {
    margin-bottom: 15px;
}

.terrain-effects h4 {
    margin-bottom: 12px;
    color: #e0e0e0;
    font-size: 16px;
}

.effects-controls {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
}

.test-btn {
    grid-column: 1 / -1;
    background-color: #9C27B0;
    color: white;
}

.test-btn:hover {
    background-color: #7B1FA2;
}

.lighting-btn,
.water-btn,
.disable-btn {
    padding: 8px 12px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 12px;
    font-weight: bold;
    transition: all 0.3s ease;
}

.lighting-btn {
    background-color: #FF9800;
    color: white;
}

.lighting-btn:hover {
    background-color: #F57C00;
}

.water-btn {
    background-color: #2196F3;
    color: white;
}

.water-btn:hover {
    background-color: #1976D2;
}

.disable-btn {
    background-color: #9E9E9E;
    color: white;
}

.disable-btn:hover {
    background-color: #757575;
}

.terrain-details {
    padding: 12px;
    background-color: #2a2a2a;
    border-radius: 6px;
    margin-bottom: 15px;
    font-size: 14px;
    color: #e0e0e0;
}

.terrain-status {
    padding: 12px;
    background-color: #2a2a2a;
    border-radius: 6px;
    border-left: 4px solid #dee2e6;
    font-size: 14px;
    color: #e0e0e0;
}

.status-unknown {
    color: #6c757d;
}

.status-ready {
    color: #17a2b8;
    font-weight: bold;
}

.status-loading {
    color: #ffc107;
    font-weight: bold;
}

.status-success {
    color: #28a745;
    font-weight: bold;
}

.status-error {
    color: #dc3545;
    font-weight: bold;
}

.status-cleared {
    color: #6c757d;
    font-weight: bold;
}

/* 滚动条样式 */
.services-grid::-webkit-scrollbar {
    width: 6px;
}

.services-grid::-webkit-scrollbar-track {
    background: #333;
    border-radius: 3px;
}

.services-grid::-webkit-scrollbar-thumb {
    background: #666;
    border-radius: 3px;
}

.services-grid::-webkit-scrollbar-thumb:hover {
    background: #888;
}

.status-disabled {
    color: #6c757d;
    font-weight: bold;
}
</style>
